10. Updating UI Elements
Updating UI Elements Heading
Dynamic UI Updates
ND#0001 C3 L4 A08 Updating UI Elements
Updating UI Elements Example Prep
Here is what it would look like to use chained GET and POST requests to retrieve information from our animal Web API, and then update DOM elements accordingly:
Updating UI Elements Heading Example
HTML
<label for="animal">Enter the name of your favorite animal</label>
<input id="animal" name="animal">
<textarea id="favorite" placeholder="Enter your favorite thing about your favorite animal" rows="9" cols="50"></textarea>
<button id = "generate">GO</button>
JS
document.getElementById('generate').addEventListener('click', performAction);
function performAction(e){
const newAnimal = document.getElementById('animal').value;
const favFact = document.getElementById('favorite').value;
getAnimal('/animalData',)
// New Syntax!
.then(function(data){
// Add data
console.log(data);
postData('/addAnimal', {animal:data.animal, fact: data.fact, fav:favFact} );
})
.then(
updateUI()
)
}
const updateUI = async () => {
const request = await fetch('/all');
try{
const allData = await request.json();
document.getElementById('animalName').innerHTML = allData[0].animal;
document.getElementById('animalFact').innerHTML = allData[0].facts;
document.getElementById('animalFav').innerHTML = allData[0].fav;
}catch(error){
console.log("error", error);
}
}
Updating UI Elements Heading Example Summary
Notice how calling the function to update the UI is the last thing we do -- this is because the update UI function depends on data from each of the other functions, so each Promise must be resolved successfully before we can update the UI. This demonstrates why native Promises and the Fetch API are such powerful tools for Asynchronous JavaScript.